package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.model.BusinessApplication;
import cn.edu.tju.elm.service.BusinessApplicationService;
import cn.edu.tju.core.security.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/business-applications")
@Tag(name = "开店申请管理", description = "提供开店申请的提交、修改、审核等功能")
public class BusinessApplicationController {

    @Autowired
    private BusinessApplicationService businessApplicationService;

    @Autowired
    private UserService userService;

    @PostMapping("")
    @Operation(summary = "提交开店申请", description = "用户提交开店申请")
    public HttpResult<BusinessApplication> submitApplication(@RequestBody BusinessApplication application) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            BusinessApplication savedApplication = businessApplicationService.submitApplication(application);
            return HttpResult.success(savedApplication);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SUBMIT_APPLICATION_ERROR, e.getMessage());
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改开店申请", description = "用户修改自己的开店申请（仅限待审核状态）")
    public HttpResult<BusinessApplication> updateApplication(@PathVariable Long id, @RequestBody BusinessApplication application) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            BusinessApplication updatedApplication = businessApplicationService.updateApplication(id, application);
            return HttpResult.success(updatedApplication);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.UPDATE_APPLICATION_ERROR, e.getMessage());
        }
    }

    @GetMapping("/admin")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "管理员查看所有开店申请列表", description = "管理员查看所有开店申请列表")
    public HttpResult<List<BusinessApplication>> getAllApplications() {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            List<BusinessApplication> applications = businessApplicationService.findAll();
            return HttpResult.success(applications);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @GetMapping("/admin/status/{status}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "根据状态查看开店申请列表", description = "管理员根据状态查看开店申请列表")
    public HttpResult<List<BusinessApplication>> getApplicationsByStatus(@PathVariable Integer status) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            List<BusinessApplication> applications = businessApplicationService.findByStatus(status);
            return HttpResult.success(applications);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @GetMapping("/my-applications")
    @Operation(summary = "获取用户开店申请列表", description = "获取当前用户的开店申请列表")
    public HttpResult<List<BusinessApplication>> getMyApplications() {

        try {
            Optional<User> currentUserOptional = userService.getUserWithAuthorities();
            if (!currentUserOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_APPLICATION_ACCESS);
            }

            User currentUser = currentUserOptional.get();
            List<BusinessApplication> applications = businessApplicationService.findByApplicantId(currentUser.getId());
            return HttpResult.success(applications);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取开店申请详情", description = "根据ID获取开店申请详情，USER只能查看自己的申请，ADMIN可以查看所有")
    public HttpResult<BusinessApplication> getApplicationById(@PathVariable Long id) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
        }

        try {
            // 检查当前用户是否是管理员
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(authority -> "ADMIN".equals(authority.getName()));

            Optional<BusinessApplication> applicationOpt;

            if (isAdmin) {
                // 管理员可以查看所有申请
                applicationOpt = businessApplicationService.findById(id);
            } else {
                // 普通用户只能查看自己的申请
                applicationOpt = businessApplicationService.findByIdAndApplicantId(id, currentUser.getId());
            }

            if (applicationOpt.isPresent()) {
                return HttpResult.success(applicationOpt.get());
            } else {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_APPLICATION_NOT_FOUND, "开店申请不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }

    @PutMapping("/{id}/review")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "审核开店申请", description = "管理员审核开店申请")
    public HttpResult<BusinessApplication> reviewApplication(
            @PathVariable Long id,
            @RequestParam Integer status,
            @RequestParam(required = false) String reviewComment) {

        try {
            Optional<User> currentUserOptional = userService.getUserWithAuthorities();
            if (!currentUserOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_APPLICATION_ACCESS);
            }

            User currentUser = currentUserOptional.get();
            BusinessApplication reviewedApplication = businessApplicationService.reviewApplication(id, status, reviewComment, currentUser.getId());
            return HttpResult.success(reviewedApplication);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        }
    }
}